package il.technion.cs236369.webserver;

import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * This class handles sessions
 * @author Yuval and Eddie
 *
 */
public class Session {
	
	private ConcurrentHashMap<String,Object> sessionValues;		//pairs of object and names
	private SessionsHandler sessionsHandler;
	private UUID uniqueSessionID;
	
	public Session(SessionsHandler sessionsHandler){
		this.sessionValues = new ConcurrentHashMap<String,Object>();
		this.sessionsHandler = sessionsHandler;
		//create a unique ID for this session
		this.uniqueSessionID = UUID.randomUUID();
	}
		
	synchronized public void set(String name, Object val){
		//if another thread closed the session, re-open it
		if(!sessionsHandler.isSessionActive(uniqueSessionID)){
			sessionsHandler.addSession(this);
		}
		sessionValues.put(name, val);
	}
	
	/**
	 * Returns the object associated with this name in this session
	 * @param name- name associated with the object
	 * @return the object, or null if not such name
	 */
	synchronized public Object get(String name){
		//if another thread closed the session, re-open it
		if(!sessionsHandler.isSessionActive(uniqueSessionID)){
			sessionsHandler.addSession(this);
		}
		return sessionValues.get(name);
	}
	
	/**
	 * Closes session. Deletes all values and deletes the session from the active sessions list in the server
	 */
	synchronized public void invalidate(){
		sessionValues.clear();
		sessionsHandler.removeSession(uniqueSessionID);
	}
	
	synchronized public UUID getSessionID(){
		return uniqueSessionID;
	}
	
}
